{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-53e462b2a513>:11: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-53e462b2a513>:29: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-53e462b2a513>:32: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:456: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:460: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-53e462b2a513>:49: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 19508,  9278, 18378, 13421, 30227,  9547,  8103,  1436,\n",
       "          11862,  9379, 30948, 23919,   473,  8926, 31710, 21259, 10352,\n",
       "          31648, 27234, 28328, 24074, 15440,  5764, 16271, 23236, 27236,\n",
       "           2995, 19841, 13161, 30411,   763, 19158,   958, 24045,  9018,\n",
       "          22377]],\n",
       " \n",
       "        [[    1, 12333,  1338, 23573,  5338, 16627, 12571,  1592, 25791,\n",
       "          21522,  1206, 14757,  2262, 28976, 10605,  9821,  2487, 26057,\n",
       "           7672, 30862, 17629, 14025,  3911, 12018, 18918,   365, 24643,\n",
       "          29542, 19069, 20516, 26645,  8063, 16352, 11390,  2916,   469,\n",
       "          28543]],\n",
       " \n",
       "        [[    1, 20497, 10163, 30573, 24962,  1681,  7141, 31867, 25130,\n",
       "          15475,  8273,  5719,   912, 30318, 18071, 20755, 17251, 17557,\n",
       "          18977, 24487, 17478, 17010, 21247, 26161, 25048, 13653,  1981,\n",
       "           7221, 20509,  2517, 22225, 30175,  8321, 13639, 29411, 23374,\n",
       "          18908]],\n",
       " \n",
       "        [[    1, 20467, 11620,  5707,    85, 21637,   688,  7295, 22417,\n",
       "          14160,  9683,  3109,  9325,  4464,  9808,  4361, 26377,  7592,\n",
       "           1945, 18209, 17419,  4291, 21007,  2596, 11509, 12755, 29303,\n",
       "           5200,  1023, 16453,  8536, 17126, 17372,  6934, 24325,  5017,\n",
       "          22866]],\n",
       " \n",
       "        [[    1, 11850, 16139, 18957, 15054, 25209, 23578, 13107, 31689,\n",
       "           5375, 26292, 23499,  5660, 16223, 27307,   355, 24318, 24740,\n",
       "           5719, 15417,  1002, 25899, 20801,  1790,  9768,  9260,  4893,\n",
       "          17687,  4682, 24347, 19688,  9024, 17592, 29935, 12535,  6688,\n",
       "           2584]],\n",
       " \n",
       "        [[    1, 24629,  8769, 13713, 13110,  1502, 25302,  6304, 29498,\n",
       "          13531,  4383, 30836, 22799, 21753, 27651,  4978, 27832, 15796,\n",
       "          30607,  4595, 27355, 14060,   996, 28285, 18961, 18827,  4356,\n",
       "           2321, 28592, 17991, 18805, 31952, 29478, 14067, 28438, 20360,\n",
       "          29087]],\n",
       " \n",
       "        [[    1, 18632, 18968, 28895,  9299, 31331, 26748,  2449, 10751,\n",
       "          20199, 27608,  4114,  4817, 12796, 16589, 15470,  9478,  1357,\n",
       "          26938,  5087,  3503, 29490,  3367, 26306,  4189,  3665, 16814,\n",
       "          18023,  9028, 21122, 30226, 20364, 29405, 28264, 24625,  3761,\n",
       "          19144]],\n",
       " \n",
       "        [[    1, 13723, 23138, 21403, 28446, 16334, 20545, 12848, 31983,\n",
       "          29888, 21426, 25040, 27843, 28867, 26211, 19652, 22463, 31315,\n",
       "           4978, 22348, 10681, 31267, 18579, 29410, 30179,  2336, 18071,\n",
       "          26222, 10380, 28659, 13945,  9503, 14898,  6435,  1099,  9663,\n",
       "          14145]],\n",
       " \n",
       "        [[    1,  9843, 16089, 15138, 24019,  2157, 17632, 18295,  9263,\n",
       "           1692,  1399, 17040, 29845, 31704,  1319, 12114,  9210, 29518,\n",
       "          13800, 29021,  9399,  4239,  7238, 10353, 15835,  5493, 25934,\n",
       "          15468, 15998, 27088, 15636, 30488, 20945,  8483, 31810, 27668,\n",
       "           5178]],\n",
       " \n",
       "        [[    1, 20045,  2958, 28190,  9356,  2041, 21042, 19808,  1221,\n",
       "          12819, 13552, 12733, 20286,  9273, 11052, 13770, 15598, 28291,\n",
       "          30141, 14566, 12663, 20539, 21499, 30993,  3737, 13857, 15315,\n",
       "           4374, 16971, 30049, 10432,  4260, 26441, 18698, 20369, 27274,\n",
       "          28442]]], dtype=int32), 10.371715, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:22<00:00,  3.53it/s, accuracy=0.107, cost=6.92] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.06it/s, accuracy=0.108, cost=6.71]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.265123, training avg acc 0.099548\n",
      "epoch 1, testing avg loss 6.825994, testing avg acc 0.119791\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.129, cost=6.11]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.23it/s, accuracy=0.161, cost=6.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 6.434877, training avg acc 0.134064\n",
      "epoch 2, testing avg loss 6.269685, testing avg acc 0.141217\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.138, cost=5.54]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.26it/s, accuracy=0.124, cost=5.95]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.902765, training avg acc 0.149316\n",
      "epoch 3, testing avg loss 6.042222, testing avg acc 0.147894\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.53it/s, accuracy=0.153, cost=5.26]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.31it/s, accuracy=0.129, cost=5.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.564286, training avg acc 0.158628\n",
      "epoch 4, testing avg loss 5.924966, testing avg acc 0.150517\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.164, cost=4.97]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.26it/s, accuracy=0.124, cost=5.84]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 5.354387, training avg acc 0.164369\n",
      "epoch 5, testing avg loss 5.850834, testing avg acc 0.152217\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.179, cost=4.81]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.21it/s, accuracy=0.14, cost=5.78] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 5.186417, training avg acc 0.169844\n",
      "epoch 6, testing avg loss 5.818715, testing avg acc 0.151917\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:24<00:00,  3.52it/s, accuracy=0.19, cost=4.66] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.28it/s, accuracy=0.124, cost=5.75]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 5.079506, training avg acc 0.173884\n",
      "epoch 7, testing avg loss 5.808238, testing avg acc 0.153783\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.189, cost=4.61]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.25it/s, accuracy=0.129, cost=5.87]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 5.008087, training avg acc 0.176438\n",
      "epoch 8, testing avg loss 5.812047, testing avg acc 0.152751\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:22<00:00,  3.53it/s, accuracy=0.179, cost=4.58]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.23it/s, accuracy=0.134, cost=5.95]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.963687, training avg acc 0.177706\n",
      "epoch 9, testing avg loss 5.820098, testing avg acc 0.153254\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.194, cost=4.51]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.23it/s, accuracy=0.151, cost=5.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.923913, training avg acc 0.179167\n",
      "epoch 10, testing avg loss 5.829893, testing avg acc 0.152229\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:22<00:00,  3.53it/s, accuracy=0.178, cost=4.65]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.19it/s, accuracy=0.14, cost=5.8]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 4.936167, training avg acc 0.177323\n",
      "epoch 11, testing avg loss 5.899944, testing avg acc 0.149049\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.53it/s, accuracy=0.149, cost=4.95]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.24it/s, accuracy=0.145, cost=5.79]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 5.056580, training avg acc 0.168941\n",
      "epoch 12, testing avg loss 6.020234, testing avg acc 0.140963\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.53it/s, accuracy=0.0522, cost=9.89]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.21it/s, accuracy=0.0591, cost=8.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 17.496456, training avg acc 0.061407\n",
      "epoch 13, testing avg loss 9.652020, testing avg acc 0.054545\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.53it/s, accuracy=0.0617, cost=8.56]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.21it/s, accuracy=0.0538, cost=7.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 8.911634, training avg acc 0.066159\n",
      "epoch 14, testing avg loss 8.599045, testing avg acc 0.067885\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.0583, cost=8.23]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.21it/s, accuracy=0.0538, cost=7.83]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 8.247831, training avg acc 0.072526\n",
      "epoch 15, testing avg loss 8.338076, testing avg acc 0.069374\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.53it/s, accuracy=0.0353, cost=21]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.24it/s, accuracy=0.0376, cost=14.5]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 19.710833, training avg acc 0.057265\n",
      "epoch 16, testing avg loss 19.620388, testing avg acc 0.042228\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:22<00:00,  3.53it/s, accuracy=0.055, cost=11.9] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.30it/s, accuracy=0.0591, cost=9.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 13.640315, training avg acc 0.059976\n",
      "epoch 17, testing avg loss 11.398864, testing avg acc 0.047106\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:23<00:00,  3.52it/s, accuracy=0.0475, cost=10.9]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.25it/s, accuracy=0.0484, cost=9.5] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 10.774070, training avg acc 0.063212\n",
      "epoch 18, testing avg loss 10.603854, testing avg acc 0.064931\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:21<00:00,  3.54it/s, accuracy=0.055, cost=9.98] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.24it/s, accuracy=0.0376, cost=9.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 10.262059, training avg acc 0.064826\n",
      "epoch 19, testing avg loss 10.124268, testing avg acc 0.060836\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:18<00:00,  3.56it/s, accuracy=0.0563, cost=9.83]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.34it/s, accuracy=0.0538, cost=9.02]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 9.853926, training avg acc 0.065893\n",
      "epoch 20, testing avg loss 9.867109, testing avg acc 0.062831\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [02:18<00:00,  3.47s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.00020161743"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
